#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 16 15:37:44 2018

@author: 260190

@description:定期删除文件，暂定删除6天前的文件。
"""
import threading
import os

base_path = os.path.abspath(os.path.dirname(__file__))

# 删除一周前的文件
def deletefile():
    """定时删除文件
    比如今天20181013,删除一天前文件，即删除20181012前, 即删除20181011、20181010……"""
    import datetime
    import os

    def datedelta(n):
        """
        :param n:
        :return:n天前 的日期，比如20180512
        """
        ndaysago = datetime.date.today() - datetime.timedelta(days=n)  # type : date
        ndaysago = ndaysago.strftime("%Y%m%d")  # type : str
        return int(ndaysago)
    data_dir = os.path.join(base_path, 'upload')  # 待删除目录
    # print(data_dir)
    daysago = datedelta(6)  # 6天前
    # print(daysago)
    for file in os.listdir(data_dir):
        if file.endswith('.pdf') and int(file[0:8]) < daysago:
            os.remove(os.path.join(data_dir, file))
    # print(str(daysago) + "前的文件已删除！")
    global timer
    timer = threading.Timer(3600, deletefile)  # 一天运行一次代码
    timer.start()


timer = threading.Timer(2, deletefile)
timer.start()

#t0 = datetime.datetime.now()  # type:datetime
#t1 = datetime.datetime.now().strftime("%Y%m%ds")  # str
#t2 = datetime.date.today() - datetime.timedelta(days=2)  # date
#t3 = int(datetime.datetime.now().strftime("%Y%m%d"))  # int
#
